package com.justreading.netty.protobuf.codec2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Random;

/**
 * @author LYJ
 * @Description
 * @date 2021 年 11 月 06 日 下午6:59
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<MyDataInfo.MyMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception {

        //这里也阔以做类型判断
//        MyDataInfo.MyMessage.DataType dataType = msg.getDataType();
//        if(dataType == MyDataInfo.MyMessage.DataType.StudentType){
//            MyDataInfo.Student msgStudent = msg.getStudent();
//            System.out.println("客户端收到的消息: " + msgStudent.getName());
//        } else {
//            MyDataInfo.Student msgStudent = msg.getStudent();
//            System.out.println("客户端收到的消息: " + msgStudent.getName());
//        }
        MyDataInfo.Student msgStudent = msg.getStudent();
        System.out.println("客户端收到的消息: " + msgStudent.getName());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        int i = new Random().nextInt(3);
        if (i == 0) {
            MyDataInfo.Student student = MyDataInfo.Student.newBuilder().setName("林冲").build();
            MyDataInfo.MyMessage myMessage = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.StudentType).setStudent(student).build();
            ctx.channel().writeAndFlush(myMessage);
        } else {
            MyDataInfo.Worker worker = MyDataInfo.Worker.newBuilder().setName("东京教头").build();
            MyDataInfo.MyMessage myMessage = MyDataInfo.MyMessage.newBuilder().setDataType(MyDataInfo.MyMessage.DataType.WorkerType).setWorker(worker).build();
            ctx.channel().writeAndFlush(myMessage);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
    }
}
